package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.*;
import org.springframework.web.server.WebFilter;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.function.LongConsumer;

import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;

@Configuration
public class RouterFunctionsWebFlux {


    @Bean
    RouterFunction<ServerResponse> userRouter(HelloHandler helloHandler, WebFilter webFilter) {
        HandlerFilterFunction<ServerResponse, ServerResponse> filter = (serverRequest, next) -> {
            helloFilter(serverRequest);
            // 针对/hello 的请求进行过滤，然后在响应中添加一个Content-Type属性
            return next.handle(serverRequest);
        };

        return RouterFunctions.route(
                POST("/hello")
                        .and(accept(MediaType.APPLICATION_JSON)),
                helloHandler::hello)
//                .filter(filter)
                ;
    }

    private void helloFilter(ServerRequest request) {
    Mono<HelloHandler.User> requestMono = request.bodyToMono(HelloHandler.User.class);
    Mono<HelloHandler.User> mapped = requestMono.map(user -> user)
            .doOnSuccess(s -> System.out.println(s));
    }

    @Bean
    public RouterFunction<ServerResponse> routerFunction() {
        HandlerFilterFunction<ServerResponse, ServerResponse> filter = (serverRequest, handlerFunction) -> {
            Mono<Map> mapMono = serverRequest.bodyToMono(Map.class);
            System.out.println(mapMono);
            // 针对/hello 的请求进行过滤，然后在响应中添加一个Content-Type属性
            return ServerResponse.status(HttpStatus.OK).header("Content-Type", "text/plain; charset=utf-8").build();
        };
        return RouterFunctions.route(
                RequestPredicates.GET("/hello2").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
                request -> ServerResponse.ok().body(BodyInserters.fromObject("Hello www.xttblog")))
                .filter(filter);
    }
}